import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.*;

public class ChatHandler extends Thread{
	static Vector handlers = new Vector(3);
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	public static HashSet userlist = new HashSet();

	//String name;
	
	
	
	public ChatHandler(Socket socket) throws IOException {
		this.socket = socket;
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
		
	}

	public void run() {
		
		
		String line;
		synchronized (handlers) {
			handlers.addElement(this);
			// add() not found in Vector class
		}
		try {
			//out.println("please enter your name:");
			String name = "unknown";
			name = in.readLine();
			userlist.add(name);
			
			Iterator iniuser = userlist.iterator();
			if(iniuser.hasNext()) {
				out.println("ResetScreen");
				out.flush();
			}
			while(iniuser.hasNext()) {
				out.println("RefreshList");
				out.flush();
				out.println(iniuser.next());
				out.flush();
			}

			while (!(line = in.readLine()).equalsIgnoreCase("/quit")) {
				for (int i = 0; i < handlers.size(); i++) {
					synchronized (handlers) {
						
						ChatHandler handler = (ChatHandler) handlers
								.elementAt(i);
						if(line.equals("LEAVE")) {
							handler.out.println(name  + " left the room!");
							handler.out.flush();
							userlist.remove(name);
						}
						else {
							handler.out.println(name + ": " + line);
							handler.out.flush();
						}
						Iterator user = userlist.iterator();
						if(user.hasNext()) {
							handler.out.println("ResetScreen");
							handler.out.flush();
						}
							
						while(user.hasNext()) {
							handler.out.println("RefreshList");
							handler.out.flush();
							handler.out.println(user.next());
							handler.out.flush();
						}
						//System.out.println(line);
						//gui.presentArea.append(name + ":" + line + '\n');
					}
				}
			}
			
			
			
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				socket.close();
			} catch (IOException ioe) {
			} finally {
				synchronized (handlers) {
					handlers.removeElement(this);
				}
			}
		}
	}
	

	
}